package com.app.service.impl;

import com.app.entity.User;
import com.app.mapper.UserMapper;
import com.app.service.UserService;
import com.app.util.Result;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.jws.soap.SOAPBinding;
import java.util.List;

/**
 * @author by lkg on 2021/3/23
 */
@Service
public class UserServiceImpl implements UserDetailsService, UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    //用户登陆方法
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("username", username);
        User user = userMapper.selectOne(queryWrapper);
        return user;
    }

    @Override
    public Result updateAdmin(User user) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("username", user.getUsername());
        User user1 = userMapper.selectOne(queryWrapper);
        if (user1 == null) {
            return Result.fail("账号不存在！");
        }
        user1.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
        userMapper.updateById(user1);
        return Result.success();
    }

    @Override
    public Result findAllUser(String username) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("state", 1);
        if (StringUtils.isNotEmpty(username)) {
            queryWrapper.like("username", username);
        }
        List<User> lists = userMapper.selectList(queryWrapper);
        return Result.success(lists);
    }

    @Override
    public Result findUserNumByAdmin() {
        return Result.success(userMapper.selectCount(new QueryWrapper<User>().eq("state", 1)));
    }

    @Override
    public Result updateUser(User user) {
        userMapper.updateById(user);
        return Result.success();
    }
}
